package com.richapp.launcher.scene.actions;

import com.alibaba.fastjson.JSONObject;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.scene.SceneServer;
import com.richapp.launcher.scene.abstracts.SceneAbstractAction;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.command.ControlDeviceCmd;

public class SceneOpenAction extends SceneAbstractAction {
	private DeviceModelDao deviceModelDao = null;
	public SceneOpenAction() {
	}

	@Override
	public int getActionType() {
		return SCENE_ACTION_TYPE_OPEN;
	}

	@Override
	public void doAction() {
		DeviceModel device = getDevice();
		if(device != null){
			DeviceModel deviceModel=null;
			DeviceModelDao deviceModelDao=new DeviceModelDao(SceneServer.getInstance().getContext());
			deviceModel=deviceModelDao.getByCpuIdDeviceIdDeviceNumber(device.getBoxCpuId(),device.getDeviceId(),device.getDeviceNumber(),device.getWay());
			if (deviceModel!=null){
				if ("FF".equals(deviceModel.getDeviceStatus())||"C0".equals(deviceModel.getDeviceStatus())){
					return;
				}
			}
			BoxModel boxModel = new BoxModelDao(SceneServer.getInstance().getContext()).getCurrentBox();
			if(boxModel.getBoxCpuId().equals(device.getBoxCpuId())){
				if(!GatewaytConstant.INSTRUCTION_OPEN_MACHINE_STR.equals(device.getDeviceStatus())){
					ControlDeviceCmd.getInstance().openDevice(device.getBoxCpuId(), device.getDeviceId(), device.getDeviceNumber(),device.getWay());
				}
//				ControlDeviceCmd.getInstance().openDevice(device.getBoxCpuId(), device.getDeviceId(), device.getDeviceNumber(),device.getWay());
			}else{
				//同步到其他主机
				JSONObject obj = new JSONObject();
				obj.put("type", 3);
				obj.put("userName", boxModel.getUserName());
				obj.put("currentBoxCpuId", boxModel.getBoxCpuId());
				obj.put("boxCpuId", device.getBoxCpuId());
				obj.put("deviceId", device.getDeviceId());
				obj.put("deviceNumber", device.getDeviceNumber());

				obj.put(MsgConstant.HEAD_IS_REPLY,"true");
				//发送服务器
				RemoteClient.getInstance().sendMessage(obj.toJSONString());
				//发送其他机顶盒
				BoxServer.getInstance().sendAllBoxMessage(obj.toJSONString());
			}
		}
		
	}
}
